/**
 * @intro: 保存商品信息
 */

import React, { Component } from 'react';
// import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import PageTitle from '../../../components/page-title';
import MUtil from '../../../utils/mm';
import Product from '../../../service/product-service';
import CategorySelect from './category-selector';
import FileUploader from '../../../utils/file-uploader'
import RichEditor from '../../../utils/rich-editor';

import './save.scss';

const _mm = new MUtil()
const _product = new Product()

class ProductSave extends Component {
	constructor(props) {
		super(props);
		this.state = {
			id: this.props.match.params.pid,
			name: '',
			subtitle: '',
			categoryId: 0,
			parentCategoryId: 0,
			subImages: [],
			price: '',
			stock: '',
			detail: '',
			status: 1, // 这里商品状态1为在售
		};
	}

	componentDidMount() {
		this.loadPruduct()
	}

	loadPruduct() {
		// 有id的时候表示编辑功能需要表单回填
		if(this.state.id) {
			_product.getProduct(this.state.id).then(res=>{
				if(res.subImages && res.subImages.length > 0) {
					let images = res.subImages.split(',');
					res.subImages = images.map((image,key) => {
						return {
							uri: image,
							url: `${res.imageHost}${image}`,
							key: key,
						}
					})
				}
				if(res.detail) {
					res.defaultDetail = res.detail
				}
				this.setState(res)
			},errMsg=>{
				_mm.errorTips(errMsg)
			})
		}
	}

	// 商品名称、描述、价格
	onValueChange(e) {
		let name = e.target.name,
				value = e.target.value.trim();
		this.setState({
			[name]: value
		})
	}

	// 品类选择器变化
	onCategoryChange(categoryId, parentCategoryId) {
		this.setState({
			categoryId: categoryId,
			parentCategoryId: parentCategoryId
		})
	}

	// 上传图片成功
	onUploadSuccess(res) {
		let subImages = this.state.subImages;
		subImages = [...this.state.subImages,res]
		this.setState({
			subImages: subImages
		})
	}

	// 上传图片失败
	onUploadError(errmsg) {
		_mm.errorTips(errmsg)
	}

	// 删除图片
	onImageDelete(e) {
		let index = parseInt(e.target.getAttribute('index')),
				subImages = this.state.subImages;
		subImages.splice(index, 1);
		this.setState({
			subImages: subImages
		})
	}

	// 富文本改变
	onDetailValueChange(value) {
		this.setState({
			detail: value
		})
	}

	getSubImagesString() {
		return this.state.subImages.map((image) => {
			return image.uri
		}).join(',');
	}

	// 这是提交表单
	onSubmit(e) {
		let product = {
			name: this.state.name,
			subtitle: this.state.subtitle,
			categoryId: parseInt(this.state.categoryId),
			subImages: this.getSubImagesString(),
			price: parseInt(this.state.price),
			stock: parseInt(this.state.stock),
			detail: this.state.detail,
			status: this.state.status,
		}

		let productCheckResult = _product.checkProduct(product);
		if(this.state.id) {
			product.id = this.state.id
		}
		if(productCheckResult.status) {
			_product.saveProduct(product).then(res=>{
				_mm.successTips(res)
				this.props.history.push('/product/index')
			},errMsg=>{
				_mm.errorTips(errMsg)
			})
		} else {
			_mm.errorTips(productCheckResult.msg)
		}
	}


	render() {
		return (
			<div id="page-wrapper">
				<PageTitle title={this.state.id?'编辑商品':'添加商品'} />
				<div className="form-horizontal">
					<div className="form-group">
						<label className="col-sm-2 control-label">商品名称</label>
						<div className="col-sm-5">
							<input type="email" className="form-control"
								placeholder="请输入商品名称"
								name='name'
								value={this.state.name}
								onChange={(e) => this.onValueChange(e)}
							/>
						</div>
					</div>
					<div className="form-group">
						<label className="col-sm-2 control-label">商品描述</label>
						<div className="col-sm-5">
							<input type="text" className="form-control"
								placeholder="请输入商品描述"
								name='subtitle'
								value={this.state.subtitle}
								onChange={(e) => this.onValueChange(e)}
							/>
						</div>
					</div>
					<div className="form-group">
						<label className="col-sm-2 control-label">所属分类</label>
						<CategorySelect
							categoryId = {this.state.categoryId}
							parentCategoryId = {this.state.parentCategoryId}
							onCategoryChange = {
								(categoryId, parentCategoryId) => {
									this.onCategoryChange(categoryId, parentCategoryId)
								}
							}
						/>
					</div>
					<div className="form-group">
						<label className="col-sm-2 control-label">商品价格</label>
						<div className="col-sm-2">
							<div className="input-group">
								<input type="number" className="form-control"
									placeholder="请输入商品价格"
									value={this.state.price}
									name='price'
									onChange={(e) => this.onValueChange(e)}
								/>
								<span className="input-group-addon">元</span>
							</div>
						</div>
					</div>
					<div className="form-group">
						<label className="col-sm-2 control-label">商品库存</label>
						<div className="col-sm-2">
							<div className="input-group">
								<input type="number" className="form-control"
									placeholder="请输入商品库存"
									value={this.state.stock}
									name='stock'
									onChange={(e) => this.onValueChange(e)}
								/>
								<span className="input-group-addon">件</span>
							</div>
						</div>
					</div>
					<div className="form-group">
						<label className="col-sm-2 control-label">商品图片</label>
						<div className="col-sm-10">
							{
								this.state.subImages && this.state.subImages.length? this.state.subImages.map((image,index) => {
									return(
										<div className='img-con'>
											<img src={image.url} key={index} alt="" />
											<i className="fa fa-close" index={index} onClick={e => this.onImageDelete(e)}></i>
										</div>
									)
								}): (<div>请上传图片</div>)
							}
						</div>
						<div className="col-md-10 col-md-offset-2 file-upload-con">
							<FileUploader onSuccess={res => this.onUploadSuccess(res)} onError={errMsg => this.onUploadError(errMsg)} />
						</div>
					</div>
					<div className="form-group">
						<label className="col-sm-2 control-label">商品详情</label>
						<div className="col-sm-10">
							<RichEditor
								detail = {this.state.detail}
								defaultDetail={this.state.defaultDetail}
								onValueChange = {value => this.onDetailValueChange(value)}
							/>
						</div>
					</div>
					<div className="form-group">
						<div className="col-sm-offset-2 col-sm-10">
							<button type="submit" className="btn btn-primary"
								onClick={(e) => {this.onSubmit(e)}}
							>提交</button>
						</div>
					</div>
				</div>
			</div>
		);
	}
}

export default ProductSave;
